from ..base import base
from flask import render_template, request
from flask_jwt_extended import jwt_required, get_jwt_identity, current_user
from flask import g, jsonify
from ..models import Resource, Organization, ResourceType, User
from sqlalchemy import text
from app import setup_logger
from .. import captcha
from app.utils.cache import cache

logger = setup_logger(__name__)

def setAccessable(resource, permitedIDList):
    if resource.ID not in permitedIDList:
        resource.HIDDEN = True
    
    for child in resource.children:
        setAccessable(child, permitedIDList)

@base.route('/getRouters')
@jwt_required()
def getRouters():
    # get from cache
    cached_id = f"routers_{current_user.ID}"
    if cache.get(cached_id):
        return jsonify({'msg': '操作成功', 'code': 200, "data": cache.get('routers'), "isCache": True})

    # get from db
    
    
    resources = []
    resources += [res for org in current_user.organizations for res in org.resources if org.resources]
    resources += [res for role in current_user.roles for res in role.resources if role.resources]
    
    ids = [res.ID for res in resources]

    #allResources = Resource.query.filter(
    #    text("FIND_IN_SET(ID, :ids) > 0")).params(ids = ','.join(ids)) .all()
    
    allResources = Resource.query.join(ResourceType, Resource.ResourceType).filter(
        Resource.SYRESOURCE_ID == None).all()
    # filter resource not allowed
    # for res in allResources:
    #    setAccessable(res, ids)

    json = [res.to_router_json() for res in allResources]
    cache.set(cached_id, json)

    return jsonify({'msg': '操作成功', 'code': 200, "data": json})

@base.route('/captchaImage')
def captchaImage():
    new_captcha_dict = captcha.create()

    return jsonify({'msg': '操作成功', 'code': 200, 'img': new_captcha_dict['img'], 'uuid': new_captcha_dict['hash']})

@base.route('/alioss/upload', methods=['POST'])
def upload():
    from ..utils.alioss import AliOssUploader
    from datetime import datetime

    if 'file' not in request.files:
        return jsonify({'code': 400, 'msg': '未上传文件'})
    
    file = request.files['file']
    if file.filename == '':
        return jsonify({'code': 400, 'msg': '未选择文件'})
    
    try:
        uploader = AliOssUploader()
        # 生成OSS存储路径，可按需修改
        timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
        object_name = f"uploads/{timestamp}/{file.filename}"
        # 保存临时文件
        temp_path = f"/tmp/{file.filename}"
        file.save(temp_path)
        
        # 上传到OSS
        if uploader.upload_file(temp_path, object_name):
            file_url = uploader.get_file_url(object_name)
            return jsonify({
                'code': 200, 
                'msg': '上传成功',
                'data': {
                    'url': file_url,
                    'name': file.filename
                }
            })
        else:
            return jsonify({'code': 500, 'msg': '文件上传失败'})
    except Exception as e:
        return jsonify({'code': 500, 'msg': f'上传出错: {str(e)}'})
     